import config from "../../utils/config.js";
// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    opacity: 0, //搜索栏透明度参数
    color: "white", //搜索栏字体图标颜色参数,
    user: '', //用户信息
    code: '', //微信授权code
    regionflag: false, //城市模态框显示隐藏参数.
    cateId: 0, //商品分类ID，0新车，1二手车
    page: 1, //当前页数，
    pageSize: 6, //页数记录数,
    bannerList: [], //轮播数组，
    cateList: [], //品牌优选数组
    recommendGoods: [], //为你推荐数组，
    likeList: [], //猜你喜欢数组
    userinfoflag: false, //授权登录模态框
    phoneNumberflag: false, //授权手机号绑定模态框
    phone: '', //当前手机号,
    city: '', //当前城市，
    brand: false, //品牌车系模态框显示隐藏参数,true显示false隐藏
    brandchlid: false, //车系模态框显示隐藏参数,true显示false隐藏
    brandList: [], //品牌车系数组,
    brandListchild: [], //当前选中品牌的车系数组
    brandindex: [], //当前选中品牌index
    brandvalue: {}, //当前选中车系对象
    longitude: '', //用户位置经度
    latitude: '', //用户位置纬度
    advLip: '', //首页广告图
    platExplain: {},//免责声明富文本
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;
    if (options.scene) {
      var scene = decodeURIComponent(options.scene);
      let infoArr = [];
      infoArr = scene.split(',');
      if (infoArr[0].split('=')[0] == 'share_code') {
        wx.setStorageSync('sharecode', infoArr[0].split('=')[1])
      }
      // wx.setStorageSync('sharecode', options.scene.share_code)
    }
    if (wx.getStorageSync('token')) {
      config.apihead.token = wx.getStorageSync('token')
      this.getHomeData();
    } else {
      wx.hideTabBar();
      that.setData({
        userinfoflag: true
      })
    }
    if (wx.getStorageSync('phone')) {
      that.setData({
        phone: wx.getStorageSync('phone')
      })
    } else {
      wx.hideTabBar();
      that.setData({
        phoneNumberflag: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    const that = this;
    that.getShopCate();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (!wx.getStorageSync('phone')) {
      wx.login({
        success(telRes) {
          config.posthttp('api/v1/minSessionKey', {
            code: telRes.code
          }, (res) => {
            wx.setStorageSync('sessionKey', res.data.result.session_key)
          })
        }
      })
    }


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  getHomeData: function() {
    const that = this;
    config.posthttp('api/v1/getHomeData', {
      cate_id: that.data.cateId,
      page: that.data.page,
      page_size: that.data.pageSize
    }, (res) => {
      console.log(res);
      wx.setStorageSync('city', res.data.location.address_detail.city)
      that.setData({
        advLip: res.data.advLip[0],
        bannerList: res.data.bannerList,
        recommendGoods: res.data.recommendGoods,
        likeList: res.data.likeList,
        cateList: res.data.cateList,
        city: wx.getStorageSync('city'),
        longitude: res.data.location.point.x,
        latitude: res.data.location.point.y,
        platExplain: res.data.platExplain[0].content.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;" ')
      })
    })
  },
  onPageScroll: function(e) { //滚动事件，搜索栏透明度及字体随滚动改变
    let scrolltop = (e.scrollTop / 180).toFixed(1);
    this.setData({
      opacity: scrolltop
    })
    if (scrolltop > 0.3) {
      this.setData({
        color: "black"
      })
    } else {
      this.setData({
        color: "white"
      })
    }

  },
  //前往新车详情
  toCarDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/CarDetail/index?goodsid=' + id,
    })
  },
  //微信授权
  bindGetUserInfo: function(e) {
    console.log(e);
    const that = this;
    if (e.detail.errMsg == "getUserInfo:ok") {
      that.setData({
        userinfoflag: false
      })
      wx.login({
        success(telRes) {
          const code = telRes.code;
          that.setData({
            code: code
          });
          config.posthttp('api/v1/minSessionKey', {
            code: code
          }, (res) => {
            wx.setStorageSync('sessionKey', res.data.result.session_key)
            const sessionKey = res.data.result.session_key
            wx.getUserInfo({
              lang: 'zh_CN',
              success: function(e) {
                config.posthttp('api/v1/minLogin', {
                  encrypt: e.encryptedData,
                  iv: e.iv,
                  session_key: sessionKey,
                  share_code: wx.getStorageSync('sharecode')
                }, (ress) => {
                  wx.removeStorageSync('sharecode')
                  config.apihead.token = ress.data.login_token;
                  wx.setStorageSync('token', ress.data.login_token)
                  that.getHomeData();
                })
              }
            })
          })
        }
      })
    }
  },
  //手机授权
  getPhoneNumber: function(e) {
    const that = this;
    that.setData({
      phoneNumberflag: false
    })
    wx.showTabBar({});
    if (e.detail.errMsg == "getPhoneNumber:ok") {

      const phone = e.detail;
      console.log(e);
      config.posthttp('api/v1/bindUserPhone', {
        encrypt: phone.encryptedData,
        iv: phone.iv,
        session_key: wx.getStorageSync('sessionKey')
      }, (res) => {
        wx.setStorageSync('phone', res.data.userInfo.mobile)
        that.setData({
          phone: res.data.userInfo.mobile
        })

      })
    }
  },
  //城市模态框显示
  regionshow: function() {
    this.setData({
      regionflag: true
    })
  },
  //城市模态框隐藏
  regionclose: function() {
    this.setData({
      regionflag: false
    })
  },
  //品牌优选点击前往新车列表
  tonewcar: function(e) {
    const that = this;
    const keyword = e.currentTarget.dataset.id;
    wx.reLaunch({
      url: '/pages/newcar/index?keyword=' + keyword,
    })
  },
  //获取品牌车系
  getShopCate: function() {
    const that = this;
    config.posthttp('api/v1/getShopCate', {}, (res) => {
      that.setData({
        brandList: res.data.cateList,
        brandvalue: res.data.cateList[0]
      })
    })
  },
  //显示关闭品牌车系模态框
  brandclose: function() {
    const that = this;
    if (that.data.brand) {
      that.setData({
        brand: false,
      })
    } else {
      that.setData({
        brand: true,
      })
    }
  },

  //品牌车系模态框选择品牌并打开车系模态框
  brandclick: function(e) {
    const that = this;
    const index = e.currentTarget.dataset.index;
    if (that.data.brandchlid && that.data.brandindex == index) {
      that.setData({
        brandchlid: false,
      })
    } else {
      that.setData({
        brandchlid: true,
        brandListchild: that.data.brandList[index].child,
        brandindex: index
      })
    }

  },

  //车系选择
  brandchildclick: function(e) {
    const that = this;
    const index = e.currentTarget.dataset.index;
    if (index || index == 0) {
      that.setData({
        brand: false,
        brandchlid: false,
        brandvalue: that.data.brandListchild[index]
      })
    } else {
      that.setData({
        brand: false,
        brandchlid: false,
        brandvalue: that.data.brandList[that.data.brandindex]
      })
    }
  },

  //帮我买车咨询接口
  makeDatement: function() {
    const that = this;

    wx.showModal({
      title: '确认提交?',
      content: '金牌顾问将第一时间联系您',
      success(res) {
        if (res.confirm) {
          if ((/^1\d{10}$/.test(that.data.phone))) {
            config.posthttp('api/v1/makeDatement', {
              goods_id: 0,
              shop_id: 0,
              mobile: that.data.phone,
              cate_id: that.data.brandvalue.id,
              longitude: that.data.longitude,
              latitude: that.data.latitude
            }, (res) => {
              wx.showToast({
                title: '提交成功',
                icon: 'success'
              })
            })
          } else {
            wx.showToast({
              title: '手机号码有误',
              icon: "none"
            })
          }
        }
        //  else if (res.cancel) {
        //   console.log('用户点击取消')
        // }
      }
    })
  },

  //改变当前手机号码
  updatephone: function(e) {
    const that = this;
    const value = e.detail.value;
    that.setData({
      phone: value,
    })
  },

  //轮播，广告点击去向
  toevery: function(e) {
    const that = this;
    const type = e.currentTarget.dataset.type;
    const value = e.currentTarget.dataset.value
    switch (type) {
      case 1:
        wx.navigateTo({
          url: `/pages/link/index?src=${value}`,
        });
        break;
      case 2:
        wx.navigateTo({
          url: `/pages/CarDetail/index?goodsid=${value}`,
        });
        break;
      case 4:
        wx.navigateTo({
          url: value,
        });
        break;
      case 5:
        wx.navigateTo({
          url: `/pages/noticeDetail/index?id=${value}`,
        });
        break;
      case 6:
        wx.navigateToMiniProgram({
          appId: value,
          path: '',
          extraData: {},
          envVersion: 'release',
          success(res) {
          }
        })
        break;
    }
  }


})